package com.im.service.jim;

import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSONObject;
import com.im.service.common.ImConstant;
import com.im.service.domain.entity.ImUser;
import com.im.service.mapper.ImUserMapper;
import com.im.service.service.ImChatService;
import org.jim.core.ImPacket;
import org.jim.core.ImStatus;
import org.jim.core.config.ImConfig;
import org.jim.core.message.MessageHelper;
import org.jim.core.packets.*;
import org.jim.server.JimServerAPI;
import org.jim.server.config.ImServerConfig;
import org.jim.server.util.ChatKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import static org.jim.core.ImConst.STORE;
import static org.jim.core.ImConst.USER;

/**
 * @author liuzhiqiang
 */
@Component
public class SysSendService {

    protected ImServerConfig imServerConfig = ImConfig.Global.get();
    @Autowired
    private ImChatService chatService;
    @Autowired
    private ImUserMapper imUserMapper;
    private ImUser sysUser;


    @PostConstruct
    private void init() {
        sysUser = imUserMapper.selectById(ImConstant.SysUserId);
    }

    public void sendToUserId(Long userId, String content) {
        ImPacket imPacket = new ImPacket();
        imPacket.setStatus(ImStatus.C10000);
        imPacket.setCommand(Command.COMMAND_CHAT_REQ);
        ChatBody chatBody = ChatBody.newBuilder()
                .chatType(ChatType.CHAT_TYPE_PRIVATE.getNumber())
                .setCmd(Command.COMMAND_CHAT_REQ.getNumber())
                .content(content)
                .msgType(MsgType.MSG_TYPE_TEXT.getNumber())
                .setCreateTime(System.currentTimeMillis())
                .from(String.valueOf(ImConstant.SysUserId))
                .to(String.valueOf(userId))
                .build();
        chatBody.setExtras(
                new JSONObject() {
                    {
                        put("nickName", sysUser.getNickname());
                        put("avatar", sysUser.getAvatar());
                    }
                }
        );
        imPacket.setBody(new RespBody(Command.COMMAND_CHAT_REQ, chatBody).toByte());


        JimServerAPI.sendToUser(String.valueOf(userId), imPacket);
        // 记录消息
        String from = chatBody.getFrom();
        String to = chatBody.getTo();
        String sessionId = ChatKit.sessionId(from, to);
        writeMessage(STORE, USER + ":" + sessionId, chatBody);
        chatService.chatProcessing(chatBody, null);
    }

    private void writeMessage(String timelineTable, String timelineId, ChatBody chatBody) {
        if (ObjUtil.isNull(imServerConfig)) {
            imServerConfig = ImConfig.Global.get();
        }
        MessageHelper messageHelper = imServerConfig.getMessageHelper();
        messageHelper.writeMessage(timelineTable, timelineId, chatBody);
    }
}
